﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Middle.Request.Appointment;
using BenCaoXuan.Infrastructure.Dto.Middle.Response.Product;
using BenCaoXuan.Infrastructure.Dto.Middle.Response.ProductPackage;
using BenCaoXuan.Infrastructure.EFCore.MySql;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.Interface.middle;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BenCaoXuan.Service.Instance.middle
{
    [Inject_]
    public class MiddleProduct_Service: Base_Service,I_MiddleProduct_Service
    {
        private readonly Product_IOC _product_IOC;

        public MiddleProduct_Service(Product_IOC product_IOC) {
            _product_IOC = product_IOC;
        }
      
        /// <summary>
        /// 获取所有的产品套餐
        /// </summary>
        /// <param name="page">页码（默认1）</param>
        /// <param name="limit">每页条数（默认10）</param>
        /// <param name="key">搜索关键词（匹配套餐名称）</param>
        /// <returns>分页后的套餐列表及总数</returns>
        public async Task<Api_Result_Dto> Get_All_Product_Package(Fenye_Dto dto)
        {
            // 执行分页查询，同时获取总条数
            var packages = await _product_IOC._productPackage_EFCore
                .GetAll(out int total, dto.page, dto.limit,
                    false, // 不启用倒序（如需最新在前可设为true）
                    o => o.PpCreateTime, // 排序字段：创建时间
                                         // 过滤条件：状态正常且未禁用，同时匹配关键词
                    d => (d.PpStatus == 1 && d.PpIsBan == 0) &&
                         (string.IsNullOrEmpty(dto.key) || d.PpName!.Contains(dto.key))
                )
                // 转换为响应DTO
                .Select(d => new ProductPackage_Response_Dto
                {
                    id = d.PpId,
                    name = d.PpName,
                    price = d.PpPrice,
                    originalPrice = d.PpOriginalPrice,
                    duration = d.PpDuration,
                    status = d.PpStatus,
                    isBan = d.PpIsBan,
                    photo =d.PpPhoto,
                    createTime = d.PpCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    description = d.PpDescription
                }).ToListAsync();

            // 返回统一格式响应
            return Get_Result(0, "查询成功", new
            {
                total, // 总记录数
                data = packages // 当前页数据
            });
        }
        /// <summary>
        /// 获取单个产品套餐
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Get_Single_Product_Package(string? id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Get_Result(-1, "套餐ID不能为空");
            }

            // 查询套餐详情表中属于当前套餐的所有记录
            var packageDetails = await _product_IOC._productPackageDetails_EFCore.GetAll(
                d => d.PpdProductId == id
            )
            .OrderBy(d => d.PpdSort)
            .ToListAsync();


            // 获取套餐主表信息
            var packageInfo = await _product_IOC._productPackage_EFCore.GetAll(
                p => p.PpId == id
            )
            .FirstOrDefaultAsync();

            // 获取所有产品ID用于查询产品名称
            var productIds = packageDetails.Select(d => d.PpdProductId).Distinct().ToList();
            var products = await _product_IOC._product_EFCore.GetAll(
                p => productIds.Contains(p.PId)
            )
            .ToDictionaryAsync(p => p.PId, p => p.PName);

            // 组装返回数据
            var detailList = packageDetails.Select(d => new PackageDetails_Response_Dto
            {
                detailId = d.PpdId,
                productId = d.PpdProductId,
                productName = products.TryGetValue(d.PpdProductId!, out var prodName) ? prodName : "未知产品",
                singlePrice = d.PpdSinglePrice,
                sort = d.PpdSort,
                remark = d.PpdRemark
            }).ToList();

            // 组装完整的套餐信息
            var data = new ProductPackage_Response_Dto
            {
                id = packageInfo?.PpId,
                name = packageInfo?.PpName,
                price = packageInfo?.PpPrice,
                originalPrice = packageInfo?.PpOriginalPrice,
                photo = packageInfo?.PpPhoto,
                duration = packageInfo?.PpDuration,
                description = packageInfo?.PpDescription,
                details = detailList
            };

            return Get_Result(0, "查询成功", data);
        }
        /// <summary>
        /// 根据套餐ID查询套餐下的所有产品
        /// </summary>
        /// <param name="id">套餐ID</param>
        /// <returns>套餐下的产品列表</returns>
        public async Task<Api_Result_Dto> Get_Products(string? id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Get_Result(-1, "套餐ID不能为空");
            }

            var packageDetails = await _product_IOC._productPackageDetails_EFCore.GetAll(
                d => d.PpdPackageId == id
            )
            .OrderBy(d => d.PpdSort)
            .ToListAsync();

            if (!packageDetails.Any())
            {
                return Get_Result(0, "该套餐未包含任何商品");
            }

            var allProductIds = packageDetails.Select(d => d.PpdProductId).ToList();

            var validProductIds = allProductIds
                .Where(pid => !string.IsNullOrEmpty(pid))
                .Distinct()
                .ToList();

            var products = validProductIds.Any()
                ? await _product_IOC._product_EFCore.GetAll(
                    p => validProductIds.Contains(p.PId)
                ).ToDictionaryAsync(p => p.PId, p => p)
                : new Dictionary<string, Product>();

            var data = packageDetails.Select(detail =>
            {
                var productId = detail.PpdProductId;
                var productName = "未知产品";
                var productEffect = "";

                if (!string.IsNullOrEmpty(productId) && products.TryGetValue(productId, out var product))
                {
                    productName = !string.IsNullOrEmpty(product.PName)
                        ? product.PName
                        : $"未命名产品 (ID: {productId})";

                    productEffect = product.PProductEffect ?? "无功效描述";
                }
                else if (string.IsNullOrEmpty(productId))
                {
                    productName = "未指定产品";
                    productEffect = "该套餐项未关联具体产品";
                }
                else
                {
                    productName = $"不存在的产品 (ID: {productId})";
                    productEffect = "该产品可能已被删除或移动";
                }

                return new PackageDetails_Response_Dto
                {
                    detailId = detail.PpdId ?? Guid.NewGuid().ToString(), 
                    productId = productId,
                    productName = productName,
                    productEffect = productEffect,
                    singlePrice = detail.PpdSinglePrice ?? 0, 
                    sort = detail.PpdSort ?? 0, 
                    remark = detail.PpdRemark ?? "无备注信息" 
                };
            }).ToList();

            return Get_Result(0, "查询成功", data);

        }
        /// <summary>
        /// 获取所有产品
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Get_All_Products()
        {
            var products = await _product_IOC._product_EFCore
                .GetAll()
                .Where(p => p.PIsBan == 0)
                .ToListAsync();

            if (!products.Any())
            {
                return Get_Result(0, "查询成功", new List<Product_Response_Dto>());
            }

            var productIds = products.Select(p => p.PId).ToList();

            var allSpecs = await _product_IOC._productSpecs_EFCore
                .GetAll(s => productIds.Contains(s.PsProductId!) && s.PsIsBan == 0)
                .ToListAsync();

            var productsWithSpecs = products.Select(p =>
            {
                var productSpecs = allSpecs
                    .Where(s => s.PsProductId == p.PId)
                    .Select(s => new ProductSpecs_Response_Dto
                    {
                        id = s.PsId,
                        name = s.PsName,
                        price = s.PsPrice
                    })
                    .ToList();

                return new Product_Response_Dto
                {
                    id = p.PId,
                    name = p.PName,
                    isBan = p.PIsBan,
                    cover = p.PCover,
                    photo = p.PPhoto,
                    createTime = p.PCreateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                    updateTime = p.PUpdateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                    description = p.PDescription,
                    productEffect = p.PProductEffect,
                    productAttention = p.PProductAttention,
                    remark = p.PRemark,
                    specs = productSpecs
                };
            }).ToList();

            return Get_Result(0, "查询成功", productsWithSpecs);
        }
        
    }
}
